<template>
  <view class="article-list-container">
    <!-- 文章列表 -->
    <view class="article-list">
      <view v-for="item in knowledgeList" :key="item.id" class="article-card">
        <!-- 医生信息卡片 -->
        <view class="doctor-info">
          <image class="doctor-avatar" :src="item.creatorAvatar" mode="aspectFill" />
          <view class="doctor-details">
            <view class="doctor-name">{{ item.creatorName }}</view>
            <view class="doctor-title">{{ item.creatorHospatalName }} {{ item.creatorTitles }} {{ item.creatorDep }}</view>
          </view>
          <view class="follow-btn" @click="handleFollow('doc', item.creatorId, item)">
            {{ item.likeFlag === 0 ? '+ 关注' : '已关注' }}
          </view>
        </view>

        <!-- 文章内容 -->
        <view class="article-content-wrapper">
          <view class="article-title">{{ item.title }}</view>
          <view class="article-tag" v-for="topic in item.topics" :key="topic"># {{ topic }}</view>
          <view class="article-content">{{ stripHtmlTags(item.content) }}</view>
          <view class="article-images" v-if="item.coverUrl && item.coverUrl.length > 0">
            <image v-for="(img, idx) in item.coverUrl" :key="idx" class="article-img" :src="img" mode="aspectFill" />
          </view>
          <!-- 文章统计信息 -->
          <view class="article-stats">
            <view class="stat-item">{{ item.collectionNumber }} 收藏</view>
            <view class="stat-item">{{ item.commentNumber }} 评论</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载中提示 -->
    <view class="loading" v-if="loading">加载中...</view>
  </view>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits } from 'vue'
import { getKnowledgeList } from '@/api/knowledge'
import type { IKnowledgeItem } from '@/api/types/knowledge'
import { http } from '@/http/http'

// 定义props
const props = defineProps({
  type: {
    type: String,
    required: true
  },
  isDoctorArticle: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['refresh', 'load-more'])

// 知识文章列表数据
const knowledgeList = ref<IKnowledgeItem[]>([])

// 加载状态
const loading = ref(false)

// 当前页码
const currentPage = ref(1)

// 每页数量
const pageSize = ref(10)

// 总页数
const totalPages = ref(1)

// 添加移除HTML标签的函数
const stripHtmlTags = (html: string) => {
  if (!html) return '';
  return html.replace(/<[^>]*>/g, '');
}

// 获取文章列表
const fetchArticleList = async () => {
  if (loading.value) return

  loading.value = true
  try {
    const response = await getKnowledgeList({
      type: props.type,
      current: currentPage.value,
      pageSize: pageSize.value
    })

    if (response.code === 10000) {
      if (currentPage.value === 1) {
        knowledgeList.value = response.data.rows
      } else {
        knowledgeList.value = [...knowledgeList.value, ...response.data.rows]
      }
      totalPages.value = response.data.pageTotal
      return true
    } else {
      uni.showToast({
        title: response.message || '获取文章数据失败',
        icon: 'none'
      })
      return false
    }
  } catch (error) {
    console.error('获取文章数据失败:', error)
    uni.showToast({
      title: '网络异常，请重试',
      icon: 'none'
    })
    return false
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refresh = async () => {
  currentPage.value = 1
  const success = await fetchArticleList()
  if (success) {
    emit('refresh')
  }
}

// 加载更多
const loadMore = async () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    await fetchArticleList()
    emit('load-more')
  }
}

// 处理关注/取消关注操作
const handleFollow = async (type: string, id: string, item: any) => {
  try {
    const response = await http.post('/like', {
      type,
      id
    })

    if (response.code === 10000) {
      // 更新关注状态
      item.likeFlag = item.likeFlag === 0 ? 1 : 0
      uni.showToast({
        title: item.likeFlag === 1 ? '关注成功' : '取消关注成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: response.message || '操作失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('关注操作失败:', error)
    uni.showToast({
      title: '网络异常，请重试',
      icon: 'none'
    })
  }
}

// 初始加载数据
fetchArticleList()
</script>

<style scoped>
/* 文章卡片样式 */
.article-list-container {
  width: 100%;
  box-sizing: border-box;
}

.article-list {
  width: 100%;
}

.article-card {
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 3px;
  padding: 15px;
  width: 100vw;
  margin-left: -45rpx;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.doctor-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.doctor-avatar {
  width: 43px;
  height: 43px;
  border-radius: 50%;
  margin-right: 12px;
}

.doctor-details {
  flex: 1;
}

.doctor-name {
  font-size: 12px;
  font-weight: bold;
  color: #333;
}

.doctor-title {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
}

.follow-btn {
  color: #07c160;
  font-size: 12px;
  padding: 4px 10px;
  border: 1px solid #07c160;
  border-radius: 15px;
  height: 25px;
}

.article-content-wrapper {
  margin-top: 10px;
}

.article-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.article-tag {
  color: #07c160;
  font-size: 12px;
  margin-bottom: 10px;
  display: inline-block;
  margin-right: 10px;
}

.article-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

.article-images {
  display: flex;
  gap: 8rpx;
  margin-top: 16rpx;
}

.article-img {
  flex: 1;
  height: 240rpx;
  border-radius: 8rpx;
  object-fit: cover;
}

.article-stats {
  display: flex;
  font-size: 12px;
  color: #999;
}

.stat-item {
  margin-right: 15px;
}

.loading {
  text-align: center;
  padding: 10px;
  color: #999;
}
</style>